/* Copyright (C) 2010 Fredrique Samuels, fredriquesamuels@gmail.com */

/*
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "combobox.h"


namespace tri{
namespace ui{	

extComboBox::extComboBox():extLabel(){
	setStyle("DefaultTextEditStyle");
	//mComboBoxHandler = extComboBoxHandler(this);
	connect<extComboBox>(tri::PRESSED,this,&extComboBox::showPopup);
	mPopup.setSize(100,100,0);
	addComponent(&mPopup);
	mPopup.addComponent(&mItemScrollBox);
	
	mItemScrollBox.setContent(&mItemListPanel);
	mItemScrollBox.setHorizontalScrolling(false);
	
	mItemListPanel.setSize(396,190,0);
	mItemListPanel.connect<extComboBox>(tri::VALUE_CHANGED,this,&extComboBox::onItemClicked);
	
}
	
extComboBox::~extComboBox(){}
	
	
void extComboBox::update(){
	pack();
	extLabel::update();
}

void extComboBox::pack(){
	tri::TVector combo_size = getSize();
	tri::TVector popup_size = mPopup.getSize();
	tri::TVector popup_pos = mPopup.getSize();
	
	popup_size.x = combo_size.x;
	popup_pos.x =0;
	popup_pos.y = -popup_size.y-combo_size.y;
	mPopup.setPosition(popup_pos);
	mPopup.setSize(popup_size);
	mItemScrollBox.setSize(popup_size);
	
	
	mItemListPanel.setSize(popup_size);
	tri::TVector list_size = mItemListPanel.getSize();
	list_size.x = popup_size.x;
	mItemListPanel.setSize(list_size);
	mItemListPanel.pack();
	mItemScrollBox.pack();
	
}


void extComboBox::addItem(std::string item){
	mItemListPanel.addItem(item);
}

void extComboBox::removeItem(std::string item){
	mItemListPanel.removeItem(item);
}

void extComboBox::clear(){
	mItemListPanel.clear();
	setText("");
}


void extComboBox::showPopup(){
	if (!mPopup.isVisible()){
		mItemScrollBox.refresh();
		mPopup.show();
	}else{
		mPopup.hide();
	}
}

std::string extComboBox::getSelectedItem(){
	return mItemListPanel.getSelectedItem();
}

void extComboBox::onItemClicked(){
	setText(mItemListPanel.getSelectedItem().c_str());
	mPopup.hide();
	emit(tri::VALUE_CHANGED);
}
		
}
}